const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
//复制
const copyText = (text) => {
  wx.setClipboardData({
    data: text,
    success: function (res) {
      wx.showToast({
        title: '复制成功'
      });
    },
    fail: function (res) {
      wx.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  })
}
/** 通过枚举值获取字典
 * @param enumName 枚举名称
 */
const getDicByEnumName = enumName => {
  if (enumName) {
    if (enumName === 'axBooleanType') {
      return [{
          text: '是',
          value: true,
        },
        {
          text: '否',
          value: false,
        },
      ];
    } else if (enumName === 'allBooleanType') {
      return [{
          text: '全部',
          value: '',
        },
        {
          text: '是',
          value: true,
        },
        {
          text: '否',
          value: false,
        }
      ];
    } else {
      let dic = wx.getStorageSync('info').keyList;
      if (dic && dic.find) {
        const finder = dic.find(i => i.eName.toUpperCase() === enumName.toUpperCase());
        if (finder) return finder.dtoDictionaryValues;
      }
    }
  }
  return []
}

const getStandardList = (list, itemName = 'name', itemValue = 'id') => {
  let isArray = Array.isArray(list)
  if (isArray) {
    //暂时最多只接受两个元素数组,如['name','idcard']
    if (Array.isArray(itemName)) {
      if (itemName.length == 2) {
        list.forEach(item => {
          let str = ''
          if (item[itemName[1]]) str = '(' + item[itemName[1]] + ')'
          item.text = item[itemName[0]] + str
          item.value = item[itemValue]
        })
      }
    } else {
      list.forEach(item => {
        item.text = item[itemName]
        item.value = item[itemValue]
      })
    }
    return list
  }
  return []
}
/** 正则表达式验证 返回布尔值
 * @param val 需验证的值
 * @param regType 验证类型（empty,mobile,idcard）
 */
const dataRegexp = async (val, regType) => {
  let mobileRegexp = /^1[3456789]\d{9}$/;
  let idcardRegexp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  let idcardexRegexp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)|(^暂无身份证号码$)/;
  if (regType === 'empty') return !!(val === null || val === undefined || val === "")
  if (regType === 'mobile') return mobileRegexp.test(val)
  if (regType === 'idcard') {
    if (idcardRegexp.test(val) === false) {
      return false;
    } else {
      return await axios_base_get('/Common/ValidateIdcard', {
        idcard: val
      }).then(res => {
        return res.data;
      });
    }
  }
  if (regType === 'idcardex') {
    if (idcardexRegexp.test(val) === false) {
      return false;
    } else if (val !== "暂无身份证号码") {
      return await axios_base_get('/Common/ValidateIdcard', {
        idcard: val
      }).then(res => {
        return res.data;
      });
    }
  }
  if (regType === 'bankcard') {
    return verifyBankCard(val);
  }
  return true
}
/**
 * 1. 拿出卡号最后一位的校验位后，从右至左，将卡号按位编码，从0开始，判断偶数或奇数
  2. 判断逻辑--对每一位的计算规则：如果这一位是奇数位，则返回值本身，如果是偶数位，先将值乘以2得到一个数n，如果n是一位数（小于10），直接返回n，否则将n的个位数和十位数相加返回。
  3. 从右向左遍历，对每一位字符执行上面的判断逻辑，并将每一位的计算结果相加得到一个总数sum。
  4. 如果sum+校验位能够整除10，则此号码有效，否则号码无效。
 * 
 */
function verifyBankCard(num) {
  num = num.toString().split(''); //变为字符串再转数组
  if (num.length > 19 || num.length < 15) return false; //银行卡号长度为15-19
  let lastNum = parseInt(num[num.length - 1]); //取出最后一位--校验位
  num.length = num.length - 1; //删除最后一个值
  num = num.reverse(); //变为数组再颠倒

  let sum = 0; //总数
  num.forEach((elem, i) => {
    elem = parseInt(elem);
    if (i % 2 === 0) {
      let n = elem * 2;
      if (n < 10) sum += n;
      else sum += (parseInt(n / 10) + n % 10);
    } else sum += elem;
  });
  return (sum + lastNum) % 10 === 0 ? true : false;
}
//获取枚举值text
const getEnumNameByValue = (name, value) => {
  let text = ''
  if (name == 'axBooleanType') {
    if (value == true || value == 'true') text = '是'
    if (value == false || value == 'false') text = '否'
  } else {
    let keyList = wx.getStorageSync("info").keyList
    const obj = keyList && keyList.find(i => i.eName.toUpperCase() == name.toUpperCase());
    if (obj) {
      let key = obj.dtoDictionaryValues.find(i => i.value == value)
      if (key) text = key.text
    }
  }
  return text
}
const getAreaFullName = (key, treeData) => {
  const loops = (list) => {
    const len = list.length;
    for (let i = 0; i < len; i++) {
      const item = list[i];
      if (key == item.code) {
        return item.text;
      }
      const children = item.children;
      if (Array.isArray(children)) {
        const txt = loops(children);
        if (txt) {
          return item.text + txt;
        }
      }
    }
  };
  return loops(treeData);
};
module.exports = {
  formatTime,
  copyText,
  getStandardList,
  getDicByEnumName,
  getEnumNameByValue,
  getAreaFullName
}